<template>
    <PageTable ref="pageTableRef" :headers="tableHeaders" allow-search :search-form="searchForm" :loadCallable="loadCallable" :btns="btns">
    </PageTable>


    <!-- BEGIN 新增弹框 -->
    <el-dialog v-model="addManagerForm.showDialog"  :draggable="true" header="创建账号">
        <el-form ref="addManagerFormRef" :model="addManagerForm.formData"
        :rules="addManagerForm.rules"  label-width="auto">

            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="addManagerForm.formData.nickname" name="nickname"></el-input>
            </el-form-item>

            <el-form-item label="登录账号"  prop="account">
                <el-input v-model="addManagerForm.formData.account" name="account"></el-input>
            </el-form-item>

            <el-form-item label="账号级别" v-is-root="currManager"  prop="is_root">
                <el-radio-group name="is_root" v-model="addManagerForm.formData.is_root">
                    <el-radio v-for="(item, idx) in isRootRange" :label="idx">{{ item }}</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="角色" prop="role_ids">
                <el-checkbox-group v-model="addManagerForm.formData.role_ids">
                    <el-checkbox v-for="roleItem in allRole" :label="roleItem.id">{{ roleItem.name }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item label="新登录密码" prop="login_pwd">
                <el-input type="password" v-model="addManagerForm.formData.login_pwd" show-password></el-input>
            </el-form-item>

            <el-form-item label="确认登录密码" prop="login_pwd_confirmation">
                <el-input type="password" v-model="addManagerForm.formData.login_pwd_confirmation" show-password></el-input>
            </el-form-item>

            <el-button type="primary" @click="onAddSubmit(addManagerFormRef)">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 新增弹框  -->

    <!-- BEGIN 编辑弹框 -->

    <el-dialog v-model="editManagerForm.showDialog" :draggable="true" header="编辑">
        <el-form v-model="editManagerForm.formData" label-width="auto">
            <el-input v-model="editManagerForm.formData.id" type="hidden"></el-input>

            <el-form-item label="昵称">
                <el-input v-model="editManagerForm.formData.nickname"></el-input>
            </el-form-item>

            <el-form-item label="登录账号">
                <el-input v-model="editManagerForm.formData.account" readonly></el-input>
            </el-form-item>

            <el-form-item label="账号级别" v-is-root="currManager">
                <el-radio-group v-model="editManagerForm.formData.is_root">
                    <el-radio v-for="(item, idx) in isRootRange" :label="idx">{{ item }}</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="角色">
                <el-checkbox-group v-model="editManagerForm.formData.role_ids">
                    <el-checkbox v-for="roleItem in allRole" :label="roleItem.id">{{ roleItem.name }}</el-checkbox>

                </el-checkbox-group>
            </el-form-item>

            <el-button type="primary" @click="onEditSubmit">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 编辑弹框  -->

    <!-- BEGIN 修改登录密码 -->

    <el-dialog v-model="editLoginPwdForm.showDialog" :draggable="true" header="修改登录密码">
        <el-form :model="editLoginPwdForm.formData" ref="editLoginPwdFormRef" :rules="editLoginPwdForm.rules"
            label-width="auto">

            <el-input v-model="editLoginPwdForm.formData.id" type="hidden"></el-input>

            <el-form-item label="新登录密码" prop="login_pwd">
                <el-input type="password" v-model="editLoginPwdForm.formData.login_pwd" show-password></el-input>
            </el-form-item>

            <el-form-item label="确认登录密码" prop="login_pwd_confirmation">
                <el-input type="password" v-model="editLoginPwdForm.formData.login_pwd_confirmation" show-password></el-input>
            </el-form-item>

            <el-button type="primary" @click="onUpdateLoginPwdSubmit(editLoginPwdFormRef)">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 修改登录密码  -->
</template>

<script setup>
import { ref, onMounted } from 'vue'
import managerApi from '@/api/manager'
import managerCode from '@/constants/ManagerCode'
import roleApi from '@/api/role'
import PageTable from '@/components/PageTable.vue';
// import apiCode from '@/constants/ApiCode'
import msgUtil from '@/utils/msgUtil'
import managerInfo from '@/store/managerInfo.js'

// 自定义指令，有需要的话可以注册到全局
const vIsRoot = {
    created(el, bind){

        if(bind.value.is_root !== managerCode.IS_ROOT){
            el.style.display = 'none';
        }
    }
}
// pagetable的引用
const pageTableRef = ref();

// 修改登录密码formDom
const editLoginPwdFormRef = ref()
// 新增管理员formDom
const addManagerFormRef = ref()

const currManager = managerInfo();

// 管理员列表

const isRootRange = managerCode.textOfIsRoot()
// 所有角色
const allRole = ref([])
// 加载角色
function loadAllRole() {
    return roleApi.all().then(res => {
        let r = res.data.lists.map(element => {
            element.id = '' + element.id
            return element;
        });
        allRole.value = r
    })
}
const tableHeaders = [
    {
        prop: 'id',
        label: 'ID',
        width: 50
    },
    {
        prop: 'nickname',
        label: '昵称',
    },
    {
        prop: 'account',
        label: '账号',
    },
    {
        prop: 'is_root',
        label: '超级管理员',
        template(row) {
            if (row.is_root == managerCode.IS_ROOT) {
                return `<span style="color:#F56C6C;">是</span>`
            } else {
                return `<span style="color:#909399;">否</span>`
            }
        },
    },
]
const btns = {
    deleteAll: {
        text: '',
        click(ids) {
            managerApi.del(ids).then(res => {
                msgUtil.handleApiRes(res,{
                    onApiSuccess(){
                        pageTableRef.value.initPageData();
                    }
                });
            })
        }
    },
    add: {
        text: '',
        click() {
            showAddManagerForm()
        }
    },
    rowBtns: [{
        text: '编辑',
        click(rows, idx) {
            loadAllRole().then(() => {
                // 渲染默认值
                renderEditManagerFormData(rows)
                editManagerForm.value.showDialog = true
            })

        },
    }, {
        text: '修改登录密码',
        click(rows, idx) {
            editLoginPwdForm.value.showDialog = true;
            editLoginPwdForm.value.formData = resetLoginPwdForm()
            editLoginPwdForm.value.formData.id = rows.id;
        },
    }]
};
const searchForm = ref({
    formItems: [
        {
            name: 's_account',
            type: 'text',
            placeholder: '账号',
        },
        {
            name: 's_nickname',
            type: 'text',
            placeholder: '昵称',
        },
    ]
})
const loadCallable = managerApi.pageList;
// 渲染默认编辑表单
function renderEditManagerFormData(row) {
    editManagerForm.value.formData = {
        id: row.id,
        nickname: row.nickname,
        account: row.account,
        is_root: '' + row.is_root,
        role_ids: row.role_ids
    }
}

const resetAddManagerFormData = ()=>{
    return {
        nickname: '',
        account: '',
        login_pwd: '',
        login_pwd_confirmation: '',
        is_root: ''+managerCode.IS_NOT_ROOT,
        role_ids: []
    }
}

function showAddManagerForm(){
    loadAllRole();
    addManagerForm.value.formData = resetAddManagerFormData();
    addManagerForm.value.showDialog = true
}

// 新增管理员表单
const addManagerForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: resetAddManagerFormData(),
    rules : {
        nickname : [
            {required:true, message:'昵称必填',type:'string'}
        ],
        account : [
            {required:true, message:'登录账号必填',type:'string'}
        ],
        login_pwd : [
            {required:true, message:'登录密码必填',type:'string'}
        ],
        login_pwd_confirmation: [
            { required: true, message: '请确认登录密码' },
            {
                validator: (rule, value, cb) => {
                    if (value === '') {
                        cb(new Error('请确认密码'))
                    } else if (value !== addManagerForm.value.formData.login_pwd) {
                        cb(new Error('两次密码不一致'))
                    } else {
                        cb()
                    }
                }
            }]
    }
})

// 提交新增账号
function onAddSubmit(formEl){
    formEl.validate((valid, fields) => {
        if(!valid){
            return;
        }
        if (addManagerForm.value.onSubmiting) {
            return;
        }
        addManagerForm.value.onSubmiting = true;
        managerApi.add(addManagerForm.value.formData)
        .then(res=>{
            msgUtil.handleApiRes(res,{
                onApiSuccess(){
                    addManagerForm.value.showDialog = false
                    pageTableRef.value.initPageData();
                }
            })
        })
        .finally(()=>{
            addManagerForm.value.onSubmiting = false;
        })
    })

}

// 编辑管理员表单
const editManagerForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: {
        id: '',
        nickname: '',
        account: '',
        is_root: managerCode.IS_NOT_ROOT,
        role_ids: []
    }
})


const resetLoginPwdForm = () => {
    return {
        id: '',
        login_pwd: '',
        login_pwd_confirmation: ''
    }
}
// 编辑登录密码的表单
const editLoginPwdForm = ref({
    showDialog: false,
    onSubmiting: false,
    rules: {
        login_pwd: [{ required: true, message: '请输入新登录密码' }],
        login_pwd_confirmation: [
            { required: true, message: '请确认密码' },
            {
                validator: (rule, value, cb) => {
                    if (value === '') {
                        cb(new Error('请确认密码'))
                    } else if (value !== editLoginPwdForm.value.formData.login_pwd) {
                        cb(new Error('两次密码不一致'))
                    } else {
                        cb()
                    }
                }
            }]
    },
    formData: resetLoginPwdForm()
})

// 提交修改登录密码
function onUpdateLoginPwdSubmit(formEl) {

    formEl.validate((valid, fields) => {
        if(!valid){
            return;
        }
        if (editLoginPwdForm.value.onSubmiting) {
            return;
        }
        editLoginPwdForm.value.onSubmiting = true;
        managerApi.updateLoginPwd(editLoginPwdForm.value.formData)
        .then(res=>{
            msgUtil.handleApiRes(res,{
                onApiSuccess(){
                    editLoginPwdForm.value.showDialog = false
                }
            })
        })
        .finally(()=>{
            editLoginPwdForm.value.onSubmiting = false;
        })
    })

}

// 提交编辑
function onEditSubmit() {
    if (editManagerForm.value.onSubmiting) {
        return;
    }
    editManagerForm.value.onSubmiting = true
    managerApi.updateBaseInfo(editManagerForm.value.formData).then(res => {
        msgUtil.showSuccessAndAlertError(res).then(()=>{
            editManagerForm.value.showDialog = false;
            pageTableRef.value.initPageData();

        });
    }).finally(() => {
        editManagerForm.value.onSubmiting = false
    })

}
</script>